﻿// <copyright file="AnalyticsBehaviorHelpers.cs" company="Microsoft Corporation">
// Copyright (c) 2009 Microsoft Corporation All Rights Reserved
// </copyright>
// <author>Michael S. Scherotter</author>
// <email>mischero@microsoft.com</email>
// <date>2010-02-17</date>
// <summary>AnalyticsBehaviorHelpers extension methods definition</summary>

namespace Microsoft.WebAnalytics.Behaviors
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows;

    /// <summary>
    /// AnalyticsBehaviorHelpers extension methods
    /// </summary>
    public static class AnalyticsBehaviorHelpers
    {
        /// <summary>
        /// Get the TriggerActions of a particular type attached to the object
        /// </summary>
        /// <typeparam name="T">the type of TriggerAction to search for</typeparam>
        /// <param name="obj">the dependency object</param>
        /// <returns>the trigger actions of that type</returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "There is no other way to specify the type to return.")]
        public static IEnumerable<T> TriggerActions<T>(this DependencyObject obj)
        {
            var triggers = System.Windows.Interactivity.Interaction.GetTriggers(obj);

            var actions = from trigger in triggers.OfType<System.Windows.Interactivity.EventTrigger>()
                                from action in trigger.Actions.OfType<T>()
                                select action;

            return actions;
        }

        /// <summary>
        /// Get the first behavior of a specific type attached to an object
        /// </summary>
        /// <typeparam name="T">the type of behaviors</typeparam>
        /// <param name="obj">the dependency object</param>
        /// <returns>the behavior or null</returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "There is no other way to specify the type to return.")]
        public static T Behavior<T>(this DependencyObject obj)
        {
            return System.Windows.Interactivity.Interaction.GetBehaviors(obj).OfType<T>().FirstOrDefault();
        }
    }
}
